package com.wangdao.mall.controller.admin;

import com.alibaba.druid.util.StringUtils;
import com.google.gson.Gson;
import com.wangdao.mall.model.*;
import com.wangdao.mall.service.GoodsService;
import com.wangdao.mall.service.GoodsServiceImp;
import com.wangdao.mall.utils.FileUploadUtils;
import com.wangdao.mall.utils.HttpUtils;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @Author:HaiyangTian
 * @Description:
 * @Date: Created in 20:23 2020/4/30
 * @Modified By:
 */
@WebServlet("/api/admin/goods/*")
public class GoodsServlet extends HttpServlet {

    private GoodsService goodsService = new GoodsServiceImp();

    Gson gson = new Gson();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String uri = request.getRequestURI();
        String action = uri.replace("/api/admin/goods/", "");
        if ("imgUpload".equals(action)){
            ImgUpload(request,response);
        }else if ("addGoods".equals(action)){
            addGoods(request,response);
        }else if ("addType".equals(action)){
            addType(request,response);
        }else if ("updateGoods".equals(action)){
            updateGoods(request,response);
        }else if ("addSpec".equals(action)){
            addSpec(request,response);
        }else if ("deleteSpec".equals(action)){
            deleteSpec(request,response);
        }else if ("reply".equals(action)){
            reply(request,response);
        }
    }

    /**
     * 回复留言
     * @param request
     * @param response
     */
    private void reply(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String requestBody = HttpUtils.getRequestBody(request);
        ReplyMessage replyMessage = gson.fromJson(requestBody, ReplyMessage.class);
        Result result = new Result();
        if (StringUtils.isEmpty(replyMessage.getContent())){
            result.setCode(10000);
            result.setMessage("回复内容不能为空");
            response.getWriter().println(gson.toJson(result));
            return;
        }
        goodsService.reply(replyMessage);
        result.setCode(0);
        response.getWriter().println(gson.toJson(result));
    }

    private void deleteSpec(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String requestBody = HttpUtils.getRequestBody(request);
        SpecId spec = gson.fromJson(requestBody, SpecId.class);
        int row = goodsService.deleteSpec(spec);
        Result result = new Result();
        if (row == 1){
            result.setCode(0);
        }else{
            result.setCode(10000);
            result.setMessage("删除失败");
        }
        response.getWriter().println(gson.toJson(result));
    }

    /**
     * 增加规格
     * @param request
     * @param response
     */
    private void addSpec(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String requestBody = HttpUtils.getRequestBody(request);
        SpecId spec = gson.fromJson(requestBody, SpecId.class);
        int row = goodsService.addSpec(spec);
        Result result = new Result();
        if (row == 1){
            result.setCode(0);
            result.setData(spec);
        }else{
            result.setCode(10000);
            result.setMessage("规格重复，请重新添加");
        }
        response.getWriter().println(gson.toJson(result));
    }

    /**
     * 更新商品的数据
     * @param request
     * @param response
     */
    private void updateGoods(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String requestBody = HttpUtils.getRequestBody(request);
        GoodsParam goodsParam = gson.fromJson(requestBody, GoodsParam.class);
        goodsService.updateGoods(goodsParam);
        Result result = new Result();
        result.setCode(0);
        response.getWriter().println(gson.toJson(result));
    }

    /**
     * 添加商品的分类
     * @param request
     * @param response
     */
    private void addType(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String requestBody = HttpUtils.getRequestBody(request);
        Type type = gson.fromJson(requestBody, Type.class);
        int row = goodsService.addType(type);
        Result result = new Result();
        if (row == 1){
            result.setCode(0);
        }else{
            result.setCode(10000);
            result.setMessage("该商品分类已存在，请重新添加");
        }
        response.getWriter().println(gson.toJson(result));
    }

    private void addGoods(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String requestBody = HttpUtils.getRequestBody(request);
        GoodsParam goodsParam = gson.fromJson(requestBody, GoodsParam.class);
        goodsService.addGoods(goodsParam);
        Result result = new Result();
        result.setCode(0);
        response.getWriter().println(gson.toJson(result));
    }

    /**
     * 单独的文件上传，里面不含有普通的form表单数据
     * 传输文件的二进制数据就在请求体里面
     * @param request
     * @param response
     */
    private void ImgUpload(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //校验
        Result result = new Result();
        boolean content = ServletFileUpload.isMultipartContent(request);
        if (!content){
            result.setCode(10000);
            result.setMessage("这不是一个图片文件，请重新添加");
            response.getWriter().println(gson.toJson(result));
            return;
        }
        Map<String, Object> map = FileUploadUtils.parseRequest(request);
        // /upload/4/b/3/9/1/5/a/0/...
        String file = (String) map.get("file");
        //如果不设置域名端口号，系统会默认去8080的端口号去找
        //但是现在的图片信息都在8084端口号上，所以会找不到
        //此时要更改域名端口号，放在配置文件里用listener加载
        String domain = (String) getServletContext().getAttribute("domain");
        //localhost:8084/upload/4/b/3/9/1/5/a/0/...
        file = domain + file;
        result.setCode(0);
        result.setData(file);
        response.getWriter().println(gson.toJson(result));
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String uri = request.getRequestURI();
        String action = uri.replace("/api/admin/goods/","");
        if ("getType".equals(action)){
            getType(request,response);
        }else if ("getGoodsByType".equals(action)){
            getGoodsByType(request,response);
        }else if ("deleteType".equals(action)){
            deleteType(request,response);
        }else if ("deleteGoods".equals(action)){
            deleteGoods(request,response);
        }else if ("getGoodsInfo".equals(action)){
            getGoodsInfo(request,response);
        }else if ("noReplyMsg".equals(action)){
            getNoReplyMsg(request,response);
        }else if ("repliedMsg".equals(action)){
            getRepliedMsg(request,response);
        }
    }

    /**
     * 得到已回复的留言
     * @param request
     * @param response
     */
    private void getRepliedMsg(HttpServletRequest request, HttpServletResponse response) throws IOException {
        List<ReplyMessage> messages = goodsService.getRepliedMsg();
        Result result = new Result();
        result.setCode(0);
        result.setData(messages);
        response.getWriter().println(gson.toJson(result));
    }

    /**
     * 得到未回复的信息
     * @param request
     * @param response
     */
    private void getNoReplyMsg(HttpServletRequest request, HttpServletResponse response) throws IOException {
        List<Message> messages = goodsService.getNoReplyMsg();
        Result result = new Result();
        result.setCode(0);
        result.setData(messages);
        response.getWriter().println(gson.toJson(result));
    }

    /**
     * 得到商品的信息
     * @param request
     * @param response
     */
    private void getGoodsInfo(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String id = request.getParameter("id");
        Map<String,Object> goodsMap = goodsService.getGoodsInfo(id);
        GoodsInfo goodsInfo = new GoodsInfo();
        Goods goods = (Goods) goodsMap.get("goods");
        List<Spec> specs = (List<Spec>) goodsMap.get("specs");
        goodsInfo.setGoods(goods);
        goodsInfo.setSpecs(specs);
        Result result = new Result();
        result.setCode(0);
        result.setData(goodsInfo);
        response.getWriter().println(gson.toJson(result));
    }

    /**
     * 删除指定的商品
     * @param request
     * @param response
     * @throws IOException
     */
    private void deleteGoods(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String id = request.getParameter("id");
        goodsService.deleteGoods(id);
        Result result = new Result();
        result.setCode(0);
        response.getWriter().println(gson.toJson(result));
    }

    /**
     * 删除指定商品的分类
     * @param request
     * @param response
     */
    private void deleteType(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String typeId = request.getParameter("typeId");
        int row = goodsService.deleteType(typeId);
        Result result = new Result();
        if (row == 1){
            result.setCode(0);
        }else{
            result.setCode(10000);
            result.setMessage("删除失败");
        }
        response.getWriter().println(gson.toJson(result));
    }

    /**
     * 根据分类获取当前类目下的商品
     * @param request
     * @param response
     */
    private void getGoodsByType(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String typeId = request.getParameter("typeId");
        List<Goods> goodsList = goodsService.getGoodsByType(typeId);
        Result result = new Result();
        result.setCode(0);
        result.setData(goodsList);
        response.getWriter().println(gson.toJson(result));
    }

    /**
     * 获取商品分类目录
     * @param request
     * @param response
     */
    private void getType(HttpServletRequest request, HttpServletResponse response) throws IOException {
        List<Type> typeList = goodsService.getType();
        Result result = new Result();
        result.setCode(0);
        result.setData(typeList);
        response.getWriter().println(gson.toJson(result));
    }
}
